import { useQuery, UseQueryOptions, QueryKey } from 'react-query';
import JSONbig from 'json-bigint';
import { pipelinTemplateApi } from '@/api/pipeline-template';
import { DEFAULT_TMP_ID } from '@/routes/app-pipeline/stores/CONSTANTS';
import { DEFAULT_STAGES_DATA, DEFAUTL_CD_STAGE, TAB_FLOW_CONFIG } from '../stores/CONSTANTS';
import usePipelineContext from '@/routes/app-pipeline/hooks/usePipelineContext';
import { ciCdPipelineApi } from '@/api/cicd-pipelines';

type LoadStageDataProps = Omit<UseQueryOptions<unknown, unknown, Record<string, any>, QueryKey>, 'queryKey' | 'queryFn'>

type PipelineApiConfigs = {
  id:string | number
  type?: 'create' | 'modify' | 'copy'
  setTabsDataState:(...args:any[])=>void
}

function useLoadStageData(configs:PipelineApiConfigs, options?:LoadStageDataProps) {
  const {
    type = 'create',
    id,
    setTabsDataState,
  } = configs;

  const {
    tabApis = {},
    level,
  } = usePipelineContext();

  const { create: createPromise, modify: modifyPromise } = tabApis?.[TAB_FLOW_CONFIG] || { create: '', modify: '' };

  const handleSuccess = (stageObject:Record<string, any>) => {
    let stageLists = [];
    if (level === 'project') {
      if (window.location.href.includes('project-pipeline-template')) {
        stageLists = stageObject?.templateStageVOS || [];
      } else if (type === 'create' && stageObject?.name === '默认模板') {
      // 这里取消了默认加上一条cd任务的逻辑 但是如果是默认模板还是要加上 这里由于不知道怎么判断默认模板先写死
        stageLists = stageObject?.devopsCiStageVOS.concat(DEFAUTL_CD_STAGE);
      } else {
        // 这里之前是concat(stageObject.devopsCdStageVOS) 由于没有了cd 这里做了修改
        stageLists = stageObject?.devopsCiStageVOS.concat(type === 'copy' ? [] : []) || [];
      }
    } else {
      stageLists = stageObject?.templateStageVOS || [];
    }
    setTabsDataState({
      [TAB_FLOW_CONFIG]: stageLists,
    });
  };

  const getStageData = async () => {
    if (level === 'project') {
      if (type === 'create') {
        if (window.location.href.includes('project-pipeline-template')) {
          return createPromise(id);
        }
        if (id === DEFAULT_TMP_ID) {
          return Promise.resolve(DEFAULT_STAGES_DATA);
        }
        return pipelinTemplateApi.getTemplateDataById(id);
      }
      if (window.location.href.includes('project-pipeline-template')) {
        return modifyPromise(id);
      }
      let res: any;
      if (type === 'copy') {
        res = await ciCdPipelineApi.getCopyPipeline(id);
      } else {
        res = await ciCdPipelineApi.getTemplatesWhileEdits(id);
      }
      if (res?.devopsCdStageVOS?.length) {
        res?.devopsCdStageVOS?.forEach((item:any) => {
          item?.jobList?.forEach((jobItem: { type: string; metadata: any; }) => {
            if (jobItem?.type === 'cdHost') {
              const metadataObj = JSONbig.parse(jobItem.metadata.replace(/'/g, '"'));
              if (metadataObj.devopsHostDTO) {
                metadataObj.hostId = metadataObj.devopsHostDTO;
              }
              if (metadataObj.ctyunHostGroupDTO) {
                metadataObj.hostGroupId = metadataObj.ctyunHostGroupDTO;
              }
              // eslint-disable-next-line no-param-reassign
              jobItem.metadata = JSONbig.stringify(metadataObj);
            }
          });
        });
      }
      // // 如果是复制流水线 需要把部署相关的job清除
      // if (type === 'copy') {
      //   res.devopsCiStageVOS = res.devopsCiStageVOS.map((item:any) => {
      //     // eslint-disable-next-line no-param-reassign
      //     item.jobList = item.jobList.filter((jobItem:any) => {
      //       if (['chart_deploy', 'deployment_deploy', 'host_deploy'].includes(jobItem.type)) {
      //         return false;
      //       }
      //       return true;
      //     });
      //     return item;
      //   });
      // }
      return new Promise((resolve, reject) => {
        resolve(res);
      });
    }
    if (type === 'create') return createPromise(id);
    return modifyPromise(id);
  };

  return useQuery<unknown, unknown, Record<string, any>>(['app-pipeline-edit', id],
    getStageData, { ...options, onSuccess: handleSuccess, retry: 0 });
}

export default useLoadStageData;
